package io.gitee.yth.design.pattern.test.core.pattern.creational.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author yth
 * @since 2023-04-24-15:49
 */
public class DeepProtoType implements Cloneable, Serializable {

    public String name;
    public DeepCloneableTarget deepCloneableTarget;

    @Override
    public DeepProtoType clone() {
        try {
            return (DeepProtoType) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }

    public DeepProtoType deepClone() {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            oos.writeObject(this);
            try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                 ObjectInputStream ois = new ObjectInputStream(bis)) {
                return (DeepProtoType) ois.readObject();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}

class DeepCloneableTarget implements Cloneable, Serializable {

    public int num;

    @Override
    public DeepCloneableTarget clone() {
        try {
            return (DeepCloneableTarget) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}
